<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\LandingCompany;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class LandingCompanyController extends Controller
{
    /**
     * 获取落地公司列表
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $query = LandingCompany::query();
            
            // 搜索条件
            if ($request->filled('name')) {
                $query->searchByName($request->input('name'));
            }
            
            if ($request->filled('status')) {
                $query->where('status', $request->input('status'));
            }
            
            // 获取分页参数
            $page = (int) $request->input('page', 1);
            $perPage = (int) $request->input('per_page', 15);
            $perPage = max(1, min($perPage, 100)); // 限制每页数量在1-100之间
            
            // 排序
            $sortBy = $request->input('sort_by', 'name');
            $sortOrder = $request->input('sort_order', 'asc');
            
            if (in_array($sortBy, ['name', 'code', 'status', 'created_at'])) {
                $query->orderBy($sortBy, $sortOrder === 'desc' ? 'desc' : 'asc');
            } else {
                $query->orderBy('name', 'asc');
            }
            
            // 执行查询
            $result = $query->paginate($perPage, ['*'], 'page', $page);
            
            return response()->json([
                'success' => true,
                'message' => '获取落地公司列表成功',
                'data' => $result
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取落地公司列表失败：' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }

    /**
     * 获取落地公司选项（用于下拉列表）
     */
    public function options(Request $request): JsonResponse
    {
        try {
            $companies = LandingCompany::getActiveCompanies();
            
            return response()->json([
                'success' => true,
                'message' => '获取落地公司选项成功',
                'data' => $companies
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取落地公司选项失败：' . $e->getMessage(),
                'data' => []
            ], 500);
        }
    }

    /**
     * 获取单个落地公司详情
     */
    public function show(Request $request, $id): JsonResponse
    {
        try {
            $company = LandingCompany::find($id);
            
            if (!$company) {
                return response()->json([
                    'success' => false,
                    'message' => '落地公司不存在',
                    'data' => null
                ], 404);
            }
            
            return response()->json([
                'success' => true,
                'message' => '获取落地公司详情成功',
                'data' => $company
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取落地公司详情失败：' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }

    /**
     * 创建新的落地公司
     */
    public function store(Request $request): JsonResponse
    {
        try {
            // 验证请求数据
            $validatedData = $request->validate([
                'name' => 'required|string|max:200|unique:landing_companies,name',
                'short_name' => 'nullable|string|max:100',
                'code' => 'required|string|max:50|unique:landing_companies,code',
                'tax_number' => 'nullable|string|max:50',
                'address' => 'nullable|string|max:500',
                'contact_person' => 'nullable|string|max:50',
                'phone' => 'nullable|string|max:20',
                'email' => 'nullable|email|max:100',
                'status' => 'nullable|in:active,inactive',
                'remark' => 'nullable|string|max:1000'
            ]);
            
            // 设置默认状态
            $validatedData['status'] = $validatedData['status'] ?? LandingCompany::STATUS_ACTIVE;
            
            $company = LandingCompany::create($validatedData);
            
            return response()->json([
                'success' => true,
                'message' => '创建落地公司成功',
                'data' => $company
            ]);
            
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'data' => null,
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '创建落地公司失败：' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }

    /**
     * 更新落地公司信息
     */
    public function update(Request $request, $id): JsonResponse
    {
        try {
            $company = LandingCompany::find($id);
            
            if (!$company) {
                return response()->json([
                    'success' => false,
                    'message' => '落地公司不存在',
                    'data' => null
                ], 404);
            }
            
            // 验证请求数据
            $validatedData = $request->validate([
                'name' => 'required|string|max:200|unique:landing_companies,name,' . $id,
                'short_name' => 'nullable|string|max:100',
                'code' => 'required|string|max:50|unique:landing_companies,code,' . $id,
                'tax_number' => 'nullable|string|max:50',
                'address' => 'nullable|string|max:500',
                'contact_person' => 'nullable|string|max:50',
                'phone' => 'nullable|string|max:20',
                'email' => 'nullable|email|max:100',
                'status' => 'nullable|in:active,inactive',
                'remark' => 'nullable|string|max:1000'
            ]);
            
            $company->update($validatedData);
            
            return response()->json([
                'success' => true,
                'message' => '更新落地公司成功',
                'data' => $company->fresh()
            ]);
            
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'data' => null,
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '更新落地公司失败：' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }

    /**
     * 删除落地公司
     */
    public function destroy(Request $request, $id): JsonResponse
    {
        try {
            $company = LandingCompany::find($id);
            
            if (!$company) {
                return response()->json([
                    'success' => false,
                    'message' => '落地公司不存在',
                    'data' => null
                ], 404);
            }
            
            // 检查是否有相关联的发票
            if ($company->invoices()->count() > 0) {
                return response()->json([
                    'success' => false,
                    'message' => '该落地公司下存在发票记录，无法删除',
                    'data' => null
                ], 400);
            }
            
            $company->delete();
            
            return response()->json([
                'success' => true,
                'message' => '删除落地公司成功',
                'data' => null
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '删除落地公司失败：' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }
}